import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    //组件内守卫
    beforeEnter:(to,from,next)=>{

      console.log("from=",from)
      console.log("to=",to)
      next()
    }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/post',
    name: 'post',
    component: () => import('@/views/Post.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta:{
      title:"我的"
    },
    component: () => import('../views/Login.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

const flag=true
//全局前置守卫
router.beforeEach((to,from,next)=>{

  //to 要到哪个页面
  //from 从哪个页面来
  console.log("loading...")
  console.log(to.meta.title)

  if (flag){
    if (to.name=="login")next("/")  //如果已经登录flag=true 且跳转到login页面，此跳转到首页
    else next()  //正常显示页面

  }else{
    //console.log("to=",to)
    //console.log("from",from)
    //next("/login")
    if (to.name=="login")next()  //如果没有登录flag=false,且跳转到当前login页面，正常显示登录
    else next("/login")  //其它页面时，跳转到登录login页面
  }


})

//全局后置钩子
router.afterEach((to,from)=>{
  console.log("loaded...")
})
export default router
